﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;
using System.Drawing.Imaging;
using System.Drawing;

namespace NearForums.Web.Output.Handler
{
    /// <summary>
    /// Summary description for UpLoadFileHandler
    /// </summary>
    public class UpLoadFileHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //upfile , typenum
            var postFile = context.Request.Files[0];
            int typeEnum = Int32.Parse(context.Request.QueryString["typenum"].ToString());
            int userID = Int32.Parse(context.Request.QueryString["userId"].ToString());

            if (postFile != null)
            {
                try
                {

                    ////获取要保存的文件信息
                    FileInfo file = new FileInfo(postFile.FileName);
                    ////获得文件扩展名
                    string fileNameExt = file.Extension;


                    string toFilePath = @"../../Uploads/" + userID.ToString();
                    string toFileName = DateTime.Now.ToString("yyyyMMddHHmmssfffff") + "_" + typeEnum.ToString() + fileNameExt;


                    //检查保存的路径 是否有/结尾
                    if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";


                    //获得要保存的文件路径
                    string serverFileName = toFilePath + toFileName;
                    //物理完整路径                    
                    string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);

                    //检查是否有该路径  没有就创建
                    if (!Directory.Exists(toFileFullPath))
                    {
                        Directory.CreateDirectory(toFileFullPath);
                    }

                    //将要保存的完整文件名                
                    string toFile = toFileFullPath + toFileName;

                    //验证合法的文件
                    //判断是否是图片
                    if (fileNameExt == ".png" || fileNameExt == ".jpg" || fileNameExt == ".gif" || fileNameExt == ".jpeg")
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromStream(postFile.InputStream, false);
                        if (img.Height < 200 || img.Width < 200 || img.Height > 1000 || img.Width > 1000)
                        {
                            context.Response.Write("-1|InvalidImg|" + "图片的长宽 必须在200-1000像素之间，请重新上传！");
                            return;
                        }

                        //缩放图片
                        Image toImage = GetOutputSizeImage(img, 300);

                        toImage.Save(toFile);
                        context.Response.Write("1|" + @"/Uploads/" + userID.ToString() + "/" + toFileName + "|" + "文件上传成功");
                    }
                    else
                    {
                        //验证合法的文件
                        bool fileOk = true;
                        if (postFile.ContentLength > 2048000 || fileNameExt != ".pdf")
                        {
                            fileOk = false;
                        }
                        if (fileOk) {
                            postFile.SaveAs(toFile);
                            context.Response.Write("1|" + @"/Uploads/" + userID.ToString() + "/" + toFileName + "|" + "文件上传成功");
                        }
                        else
                        {
                            context.Response.Write("0|errorfile|" + "文件上传失败," + "文件格式错误或大小超出2M");
                            return;
                        }  

                    }
                }
                catch (Exception e)
                {
                    context.Response.Write("0|errorfile|" + "文件上传失败,错误原因：" + e.Message);
                }

            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private Image GetOutputSizeImage(Image imgSource, int MAX_WIDTH)
        {
            Image imgOutput = imgSource;

            Size size = new Size(imgSource.Width, imgSource.Height);
            if (imgSource.Width <= 3 || imgSource.Height <= 3) return imgSource; //3X3大小的图片不转换 

            if (imgSource.Width > MAX_WIDTH || imgSource.Height > MAX_WIDTH)
            {
                double rate = MAX_WIDTH / (double)imgSource.Width;

                if (imgSource.Height * rate > MAX_WIDTH)
                    rate = MAX_WIDTH / (double)imgSource.Height;

                size.Width = Convert.ToInt32(imgSource.Width * rate);
                size.Height = Convert.ToInt32(imgSource.Height * rate);

                imgOutput = imgSource.GetThumbnailImage(size.Width, size.Height, null, IntPtr.Zero);
            }

            return imgOutput;
        }
    }
}